import { User } from '../../models/user'
import jwt from 'jsonwebtoken'
import nodemailer from 'nodemailer'
import { connectToDatabase } from './../../db/mongo'

export default defineEventHandler(async (event) => {
  const body = await readBody(event)

  if (!body.email) {
    throw createError({
      statusCode: 400,
      statusMessage: 'EMAIL_REQUIRED'
    })
  }

  await connectToDatabase()
  
  const user = await User.findOne({ email: body.email })
  if (!user) {
    return { status: 'success' }
  }

  // 生成重置令牌
  const resetToken = jwt.sign(
    { userId: user._id },
    useRuntimeConfig().jwtSecret,
    { expiresIn: '1h' }
  )

  // 发送重置邮件
  const transporter = nodemailer.createTransport({
    host: useRuntimeConfig().smtpConfig.host,
    port: useRuntimeConfig().smtpConfig.port,
    auth: {
      user: useRuntimeConfig().smtpConfig.user,
      pass: useRuntimeConfig().smtpConfig.pass
    }
  })

  await transporter.sendMail({
    from: 'noreply@example.com',
    to: body.email,
    subject: 'Password Reset',
    html: `请点击链接重置密码：<a href="${useRuntimeConfig().public.siteUrl}/auth/reset-password?token=${resetToken}">重置密码</a>`
  })

  return {
    status: 'success',
    message: 'RESET_EMAIL_SENT'
  }
})